package com.topisv.tms.utils.lead;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.topisv.tms.entity.CustomerLead;
import com.topisv.tms.entity.CustomersOrdenoSource;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ExpressBillManage;
import com.topisv.tms.rest.qimen.util.goodsinfo.TransferHelper;
import com.topisv.tms.utils.BlankUtil;
import com.topisv.tms.utils.DateUtils;

public class LeadUtil {
	protected static Logger logger = LoggerFactory.getLogger(LeadUtil.class);

	private static List<EdiGoodsSku> getEdiGoodsSkus(String customerCode, int rows) {
		List<EdiGoodsSku> ediGoodsSkus = new ArrayList<EdiGoodsSku>();
		for (int i = 0; i < rows; i++) {
			EdiGoodsSku e = new EdiGoodsSku();
			e.setCustomerCode(customerCode);
			ediGoodsSkus.add(e);
		}
		return ediGoodsSkus;
	}

	public static List<EdiGoodsSku> getEdiGoodsSkus(CustomerLead customerLead, String customerCode, Sheet s) {
		int rows = s.getLastRowNum();// .getRows();
		List<EdiGoodsSku> ediGoodsSkus = getEdiGoodsSkus(customerCode, rows);
		List<String> sequence = new ArrayList<String>();
		if (customerLead != null) {
			String[] keys = customerLead.getParams().split(",");
			Map<String, String> maps = new HashMap<String, String>();
			for (String key : keys) {
				String[] values = key.split(":");
				maps.put(values[0], values[1]);
			}

			// 遍历excel行
			for (int i = 0; i <= rows; i++) {
				Row xSSFRow = s.getRow(i);
				int columns = xSSFRow.getLastCellNum();
				// 遍历excel列
				for (int j = 0; j < columns; j++) {
					Cell cell = xSSFRow.getCell(j);
					if (cell == null) {
						continue;
					}
					String content = ExcelUtil.getCellStringValue(cell);
					if (i == 0) {
						String value = maps.get(content);
						sequence.add(value);
						continue;
					}
					EdiGoodsSku e = ediGoodsSkus.get(i - 1);
					String title = sequence.get(j);
					if (title == null) {
						continue;
					}
					try {
						replaceParams(title, content, e);
					} catch (Exception e2) {
						logger.error("some error.",e2);
					}

				}
			}
			return ediGoodsSkus;
		}

		
		for (int i = 0; i <= rows; i++) {
			Row xSSFRow = s.getRow(i);// .getCell(i,0);
			int columns = xSSFRow.getLastCellNum();
			for (int j = 0; j < columns; j++) {
				Cell xSSFCell = xSSFRow.getCell(j);
				String content = xSSFCell.toString();
				if (i == 0) {
					sequence.add(content);
					continue;
				}
				EdiGoodsSku e = ediGoodsSkus.get(i - 1);
				String title = sequence.get(j);

				if ("货品编号".equals(title)) {
					e.setBar(content);
				} else if ("条码".equals(title)) {
					e.setSku(content);
				} else if ("商品条码".equals(title)) {
					e.setSku(content);
				} else if ("品名".equals(title)) {
					e.setSkuName(content);
				} else if ("货号".equals(title)) {
					e.setBar(content);
				} else if ("商品代码".equals(title)) {
					e.setBar(content);
				} else if ("名称".equals(title)) {
					e.setSkuName(content);
				} else if ("商品名称".equals(title)) {
					e.setSkuName(content);
				} else if ("条形码".equals(title)) {
					e.setSku(content);
				} else if ("属性".equals(title)) {
					e.setCol(content);
				} else if ("规格名称".equals(title)) {
					e.setCol(content);
				} else if ("规格代码".equals(title)) {
					e.setSpec(content);
				} else if ("商品简称".equals(title)) {
					e.setHei(content);
				} else if("奇门字段".equals(title)){
					e.setSku(content);
				} else if("批次管理".equals(title)){
				    e.setIsBatchMgmt(BlankUtil.isBlank(TransferHelper.yes2One(content), "0"));
				} else if("效期管理".equals(title)){
				    e.setIsShelfLifeMgmt(BlankUtil.isBlank(TransferHelper.yes2One(content), "0"));
				}

			}
		}
		return ediGoodsSkus;
	}

	
	private static void replaceParams(String param, String content, EdiGoodsSku e) throws Exception {
		Field[] fields = e.getClass().getDeclaredFields();
		for (int j = 0; j < fields.length; j++) { // 遍历所有属性
			String name = fields[j].getName(); // 获取属性的名字
			if (!param.equals(name)) {
				continue;
			}
			String tempContent = content;
			if ("bar".equals(name) || "sku".equals(name)) {
				if(!(content.startsWith("0")||content.endsWith("D")||content.endsWith("F"))){
					try {
						DecimalFormat df = new DecimalFormat("#");
						content = df.format(Double.valueOf(content));
					} catch (Exception e2) {
						content = tempContent;
					}
				}
			}
			
			if ("sellFlg".equals(name)) {
				try {
					DecimalFormat df = new DecimalFormat("#");
					content = df.format(Double.valueOf(content));
				} catch (Exception e2) {
					content = tempContent;
				}
			}
			if (StringUtils.equals("weight", name) || StringUtils.equals("weightPkg", name) 
					|| StringUtils.equals("weightPop", name)) {
				try {
					DecimalFormat df = new DecimalFormat(".");
					content = df.format(content);
				} catch (Exception e2) {
					content = tempContent;
				}
			}
			if (StringUtils.equals("haikwanCode", name)) {
				try {
					DecimalFormat df = new DecimalFormat("0"); 
					content = df.format(Double.valueOf(content));
				} catch (Exception e2) {
					content = tempContent;
				}
			}
			
			if ("isBatchMgmt".equals(name) || "isShelfLifeMgmt".equals(name)){
			    content = BlankUtil.isBlank(TransferHelper.yes2One(content), "0");
			}
			
			name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
			String type = fields[j].getGenericType().toString(); // 获取属性的类型
			if (type.equals("class java.lang.String")) { // 如果type是类类型，则前面包含"class "，后面跟类名
				Method m = e.getClass().getMethod("set" + name, String.class);
				m.invoke(e, content);
			} else if (type.equals("class java.lang.Integer")) {
				int index = content.indexOf(".");
				Method m = e.getClass().getMethod("set" + name, Integer.class);
				if (index > 0) {
					m.invoke(e, Integer.parseInt(content.substring(0, index)));
				} else {
					m.invoke(e, Integer.parseInt(content));
				}

			} else if (type.equals("class java.lang.Double")) {
				Method m = e.getClass().getMethod("set" + name, Double.class);
				m.invoke(e, Double.parseDouble(content));
			}
			break;
		}
	}

	private static void replaceParams(String param, String content, EdiOrder e) throws Exception {
		if (null == content || "".equals(content.trim())) {
			return;
		}
		Field[] fields = e.getClass().getDeclaredFields();

		boolean fa = false;
		for (int j = 0; j < fields.length; j++) { // 遍历所有属性
			String name = fields[j].getName(); // 获取属性的名字
			if (!param.equals(name)) {
				continue;
			}
			if ("sku".equals(name)) {
				continue;
			}
			else if(StringUtils.equals("mobile", name) || StringUtils.equals("teleph", name) || StringUtils.equals( "fromno",name) 
					 || StringUtils.equals("seawayMailNumber", name)){
				if(!(content.startsWith("0")||content.endsWith("D")||content.endsWith("F"))){
					try {
						DecimalFormat df = new DecimalFormat("#");
						content = df.format(Double.valueOf(content));
					} catch (Exception e2) {
						logger.error(e2.getMessage());
					}
				}
			} else if (StringUtils.equals("haikwanCode", name)) {
				try {
					DecimalFormat df = new DecimalFormat("0"); 
					content = df.format(Double.valueOf(content));
				} catch (Exception e2) {
				    logger.error(e2.getMessage());
				}
			}
			fa = true;
			name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
			String type = fields[j].getGenericType().toString(); // 获取属性的类型
			if (type.equals("class java.lang.String")) { // 如果type是类类型，则前面包含"class "，后面跟类名
				Method m = e.getClass().getMethod("set" + name, String.class);
				m.invoke(e, content);
			} else if (type.equals("class java.lang.Integer")) {
				int index = content.indexOf(".");
				Method m = e.getClass().getMethod("set" + name, Integer.class);
				if (index > 0) {
					m.invoke(e, Integer.parseInt(content.substring(0, index)));
				} else {
					m.invoke(e, Integer.parseInt(content));
				}

			} else if (type.equals("class java.lang.Double")) {
				Method m = e.getClass().getMethod("set" + name, Double.class);
				m.invoke(e, Double.parseDouble(content));
			} else if (type.equals("class java.util.Date")) {
				Method m = e.getClass().getMethod("set" + name, Date.class);
				m.invoke(e,DateUtils.getDate(content));
			}
			break;
		}

		if (!fa) {
			replaceParams(param, content, e.getSkulst().get(0));
		}
	}

	private static void replaceParams(String param, String content, EdiOrderItem eoi) throws Exception {
		if (null == content || "".equals(content.trim())) {
			return;
		}
		Field[] fields = eoi.getClass().getDeclaredFields();
		for (int j = 0; j < fields.length; j++) { // 遍历所有属性
			String name = fields[j].getName(); // 获取属性的名字
			if (!param.equals(name)) {
				continue;
			}
			String tempContent = content;
			if ("spec".equals(name) || "articleNumber".equals(name) || "sku".equals(name)) {
				if(!(content.startsWith("0")||content.endsWith("D")||content.endsWith("F"))){
					try {
						DecimalFormat df = new DecimalFormat("#");
						content = df.format(Double.valueOf(content));
					} catch (Exception e2) {
						content = tempContent;
					}
				}
			}
			name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
			String type = fields[j].getGenericType().toString(); // 获取属性的类型
			if (type.equals("class java.lang.String")) { // 如果type是类类型，则前面包含"class "，后面跟类名
				Method m = eoi.getClass().getMethod("set" + name, String.class);
				m.invoke(eoi, content);
			} else if (type.equals("class java.lang.Integer")) {
				Method m = eoi.getClass().getMethod("set" + name, Integer.class);
				int index = content.indexOf(".");
				if (index > 0) {
					m.invoke(eoi, Integer.parseInt(content.substring(0, index)));
				} else {
					m.invoke(eoi, Integer.parseInt(content));
				}

			} else if (type.equals("class java.lang.Double")) {
				Method m = eoi.getClass().getMethod("set" + name, Double.class);
				m.invoke(eoi, Double.parseDouble(content));
			}
			break;
		}
	}

	private static List<EdiOrder> getEdiOrders(int rows) {
		List<EdiOrder> ediOrders = new ArrayList<EdiOrder>();
		for (int i = 0; i < rows; i++) {
			EdiOrder e = new EdiOrder();
			List<EdiOrderItem> es = new ArrayList<EdiOrderItem>();
			es.add(new EdiOrderItem());
			e.setSkulst(es);
			ediOrders.add(e);
		}
		return ediOrders;
	}

	/**
	 * 设置商品订单模板功能
	 * 
	 * @param customerLead
	 * @param s
	 * @return
	 */
	public static List<EdiOrder> setEdiOrder(CustomerLead customerLead, Sheet s) {
		int rows = s.getLastRowNum();// .getRows();
		List<EdiOrder> ediOrders = getEdiOrders(rows);
		Map<Integer,String> sequence = new HashMap<Integer,String>();
		// 系统设置了模版
		if (customerLead != null) {
			String[] keys = customerLead.getParams().split(",");
			Map<String, String> maps = new HashMap<String, String>();
			for (String key : keys) {
				String[] values = key.split(":");
				maps.put(values[0], values[1]);
			}

			for (int i = 0; i <= rows; i++) {
				Row xSSFRow = s.getRow(i);// .getCell(i,0);
				if (xSSFRow == null) {
					continue;
				}
				int columns = xSSFRow.getLastCellNum();
				for (int j = 0; j < columns; j++) {
					Cell xSSFCell = xSSFRow.getCell(j);
					if (xSSFCell == null) {
						continue;
					}
					String content = ExcelUtil.getCellStringValue(xSSFCell);
					if (i == 0) {
						String value = maps.get(BlankUtil.defaultValue(content).trim());
						sequence.put(j,value);
						continue;
					}
					EdiOrder e = ediOrders.get(i - 1);
					String param = sequence.get(j);
					if (param == null) {
						continue;
					}
					try {
						replaceParams(param, content.trim(), e);
					} catch (Exception e2) {

					}
				}
			}
			return ediOrders;
		}
		// 系统没有设置模版
		for (int i = 0; i <= rows; i++) {// 列
			Row xSSFRow = s.getRow(i);// .getCell(i,0);
			if (xSSFRow == null) {
				continue;
			}
			int columns = xSSFRow.getLastCellNum();
			for (int j = 0; j < columns; j++) {
				Cell xSSFCell = xSSFRow.getCell(j);
				if (xSSFCell == null) {
					continue;
				}
				String content = xSSFCell.toString();
				if (i == 0) {
					sequence.put(j,content);
					continue;
				}
				EdiOrder e = ediOrders.get(i - 1);
				String title = sequence.get(j);
				if(title == null){
					continue;
				}
				content = content.trim();
				try {
					if ("订单编号".equals(title)) {
						e.setCustomerOrdeno(content);
					} else if ("单据编号".equals(title)) {
						e.setCustomerOrdeno(content);
					} else if ("订单号".equals(title)) {
						e.setCustomerOrdeno(content);
					} else if ("商家订单号".equals(title)) {
						e.setCustomerOrdeno(content);
					} else if ("原始单号".equals(title)) {
						e.setFromno(content);
					} else if ("原始订单号".equals(title)) {
						e.setFromno(content);
					} else if ("订单id".equals(title)) {
						e.setFromno(content);
					} else if ("商家编号".equals(title)) {
						e.setCustomerCode(content);
					} else if ("合计".equals(title)) {
						e.setActuallyPaid(Double.parseDouble(content));
					} else if ("订单金额".equals(title)) {
						e.setActuallyPaid(Double.parseDouble(content));
					} else if ("订单支付总金额".equals(title)) {
						e.setActuallyPaid(Double.parseDouble(content));
					} else if ("店铺".equals(title)) {
						e.setShopna(content);
					} else if ("网名".equals(title)) {
						e.setBunick(content);
					} else if ("会员昵称".equals(title)) {
						e.setBunick(content);
					} else if ("业务员".equals(title)) {

					} else if ("货品编号".equals(title)) {
						e.getSkulst().get(0).setArticleNumber(content);
					} else if ("商品代码".equals(title)) {
						e.getSkulst().get(0).setArticleNumber(content);
					} else if ("规格代码".equals(title)) {
						e.getSkulst().get(0).setSpec(content);
					} else if ("SKU编码".equals(title)) {
						e.getSkulst().get(0).setSku(content);
					} else if ("商品编号".equals(title)) {
						e.getSkulst().get(0).setSku(content);
					} else if ("品名".equals(title)) {
						e.getSkulst().get(0).setNam(content);
					} else if ("商品名称".equals(title)) {
						e.getSkulst().get(0).setNam(content);
					} else if ("规格".equals(title)) {
						e.getSkulst().get(0).setSiz(content);
					} else if ("规格名称".equals(title)) {
						e.getSkulst().get(0).setSiz(content);
					} else if ("实际单价".equals(title)) {
						e.getSkulst().get(0).setPri(Double.parseDouble(content));
					} else if ("单价".equals(title)) {
						e.getSkulst().get(0).setPri(Double.parseDouble(content));
					} else if ("实际金额".equals(title)) {
						e.getSkulst().get(0).setAmo(Double.parseDouble(content));
					} else if ("数量".equals(title)) {
						int index = content.indexOf(".");
						if (index > 0) {
							e.getSkulst().get(0).setQty(Integer.parseInt(content.substring(0, index)));
						} else {
							e.getSkulst().get(0).setQty(Integer.parseInt(content));
						}
					} else if ("收货人".equals(title)) {
						e.setRecena(content);
					} else if ("收件人".equals(title)) {
						e.setRecena(content);
					} else if ("收货人名称".equals(title)) {
						e.setRecena(content);
					} else if ("收货人地址".equals(title)) {
						e.setAddres(content);
					} else if ("地址".equals(title)) {
						e.setAddres(content);

					} else if ("详细地址".equals(title)) {

						e.setAddres(content);

					} else if ("收货地址".equals(title)) {
						e.setAddres(content);

					} else if ("电话".equals(title)) {
						try {
							DecimalFormat df = new DecimalFormat("#");
							content = df.format(xSSFCell.getNumericCellValue());
						} catch (Exception e2) {
							content = xSSFCell.toString();
						}
						e.setMobile(content);
						e.setTeleph(content);
					} else if ("收货人手机".equals(title)) {
						DecimalFormat df = new DecimalFormat("#");
						try {
							content = df.format(xSSFCell.getNumericCellValue());
						} catch (Exception e2) {
							content = xSSFCell.toString();
						}
						e.setMobile(content);
						e.setTeleph(content);
					} else if ("收货人电话".equals(title)) {
						DecimalFormat df = new DecimalFormat("#");
						try {
							content = df.format(xSSFCell.getNumericCellValue());
						} catch (Exception e2) {
							content = xSSFCell.toString();
						}
						e.setMobile(content);
						e.setTeleph(content);
					} else if ("邮编".equals(title)) {
						int index = content.indexOf(".");
						if (index > 0) {
							e.setPostco(content.substring(0, index));
						} else {
							e.setPostco(content);
						}

					} else if ("库位".equals(title)) {
						e.getSkulst().get(0).setStoreCode(content);
					} else if ("单价".equals(title)) {
						e.getSkulst().get(0).setPri(Double.parseDouble(content));
					} else if ("备注".equals(title)) {
						e.setBz(content);
					} else if ("商家留言".equals(title)) {
						e.setShmemo(content);
						e.setSememo(content);
					} else if ("买家留言".equals(title)) {
						e.setBumemo(content);
					} else if ("货运单号".equals(title)) {
						e.setWaybillNo(content);
					} else if ("物流单号".equals(title)) {
						e.setWaybillNo(content);
					} else if ("运单号".equals(title)) {
						e.setWaybillNo(content);
					} else if ("货运方式".equals(title)) {
						e.setCaname(content);
					} else if ("物流公司".equals(title)) {
						e.setCaname(content);
					} else if ("省份".equals(title)) {
						e.setProvna(content);
					} else if ("城市".equals(title)) {
						e.setCityco(content);
					} else if ("地区".equals(title)) {
						e.setDistna(content);
					}
				} catch (Exception e2) {
					e.setGymemo("0");

				}
			}
		}
		return ediOrders;
	}

	public static List<String> getTop(Sheet s) {
		List<String> sequence = new ArrayList<String>();
		int rows = s.getLastRowNum();// .getRows();
		for (int i = 0; i <= rows; i++) {// 列
			Row xSSFRow = s.getRow(i);// .getCell(i,0);
			if (xSSFRow == null) {
				continue;
			}
			int columns = xSSFRow.getLastCellNum();
			for (int j = 0; j < columns; j++) {
				Cell xSSFCell = xSSFRow.getCell(j);
				if (xSSFCell == null) {
					continue;
				}
				String content = xSSFCell.toString();
				if (i == 0) {
					sequence.add(content);
					continue;
				}
			}
		}
		return sequence;
	}
	/**
	 * 获取导入模板的头部（首行）信息 LiBin
	 * @param s 工作表
	 * @return excel头部集合
	 */
	public static List<String> getTopNew(Sheet s) {
		List<String> sequence = new ArrayList<String>();
		Row xSSFRow = s.getRow(0);//只获取首行
		if (xSSFRow == null) {
			return sequence;
		}
		for (int j = 0; j <  xSSFRow.getLastCellNum(); j++) {
			Cell xSSFCell = xSSFRow.getCell(j);
			if (xSSFCell == null) {
				continue;
			}
			sequence.add(xSSFCell.toString());
		}
		return sequence;
	}
	
	/**
	 * 订单汇总
	 * 
	 * @param ediOrders
	 * @return
	 */
	public static Map<String, EdiOrder> getEdiOrders(List<EdiOrder> ediOrders) {
		Map<String, EdiOrder> maps = new HashMap<String, EdiOrder>();
		for (EdiOrder e : ediOrders) {
			String ordeno = e.getCustomerOrdeno();
			if (ordeno == null || "".equals(ordeno.trim())) {
				continue;
			}
			if (maps.get(ordeno) == null) {
				maps.put(ordeno, e);
			} else {
				EdiOrder tempEdiOrder = maps.get(ordeno);
				List<EdiOrderItem> eis = tempEdiOrder.getSkulst();
				boolean fa = true;
				for (EdiOrderItem ei : eis) {
					if (e.getSkulst().get(0).getSku() == null) {
						if (e.getSkulst().get(0).getSpec() == null) {
							if (e.getSkulst().get(0).getArticleNumber().equals(ei.getArticleNumber())) {
								ei.setQty(ei.getQty() + e.getSkulst().get(0).getQty());
								fa = false;
								break;
							}
						} else {
							if (e.getSkulst().get(0).getSpec().equals(ei.getSpec())) {
								ei.setQty(ei.getQty() + e.getSkulst().get(0).getQty());
								fa = false;
								break;
							}
						}

					} else {
						if (e.getSkulst().get(0).getSku().equals(ei.getSku())) {
							ei.setQty(ei.getQty() + e.getSkulst().get(0).getQty());
							fa = false;
							break;
						}
					}
				}
				if (fa) {
					eis.addAll(e.getSkulst());
				}
			}
		}
		return maps;
	}

	/**
	 * 将curEdiOrder的sku合并到preEdiOrder
	 * @param preEdiOrder
	 * @param curEdiOrder 
	 */
	public static void mergeOrderSku(EdiOrder preEdiOrder, EdiOrder curEdiOrder) {
		List<EdiOrderItem> eis = preEdiOrder.getSkulst();
		for (EdiOrderItem ei : curEdiOrder.getSkulst()) {
			mergeOrder(eis, ei);
		}
	}

	public static void mergeOrder(List<EdiOrderItem> eis, EdiOrderItem tempediOrderItem) {
		boolean fa = true;
		for (EdiOrderItem ei : eis) {
			if (tempediOrderItem.getSku() == null) {
				if (tempediOrderItem.getSpec() == null) {
					if (tempediOrderItem.getArticleNumber().equals(ei.getArticleNumber())) {
						ei.setQty(ei.getQty() + tempediOrderItem.getQty());
						fa = false;
						break;
					}
				} else {
					if (tempediOrderItem.getSpec().equals(ei.getSpec())) {
						ei.setQty(ei.getQty() + tempediOrderItem.getQty());
						fa = false;
						break;
					}
				}

			} else {
				if (tempediOrderItem.getSku().equals(ei.getSku())) {
					ei.setQty(ei.getQty() + tempediOrderItem.getQty());
					fa = false;
					break;
				}
			}
		}
		if (fa) {
			eis.add(tempediOrderItem);
		}
	}

	/**
	 * 按条件分组,每组的order都是应该合并的
	 * @param rsMap
	 * @param order
	 * @param cos
	 * @throws Exception
	 */
	public static void groupOrder(Map<String, List<EdiOrder>> rsMap, EdiOrder order, CustomersOrdenoSource cos) throws Exception {
		StringBuilder sb = new StringBuilder();
		List<String> mergeParams = new ArrayList<String>();
		mergeParams.addAll(Arrays.asList(cos.getMergeOrdenos().split(":")));
		mergeParams.add(MERGE_PARAM_CUSTOMRE);// 必须是同一个商家的才合单
		for (String mergeParam : mergeParams) {
			sb.append(BeanUtils.getProperty(order, mergeParam)).append(MERGE_PARAM_SPLITER);
		}
		String mergeKey = sb.toString();
		List<EdiOrder> orders = rsMap.get(mergeKey);
		if (orders == null) {
			orders = new ArrayList<EdiOrder>();
			rsMap.put(mergeKey, orders);
		}
		orders.add(order);
	}

	public static List<EdiOrder> mergeOrder(Map<String, List<EdiOrder>> rsMap) {
		List<EdiOrder> orders = new ArrayList<EdiOrder>();
		for (Map.Entry<String, List<EdiOrder>> entry : rsMap.entrySet()) {
			List<EdiOrder> value = entry.getValue();
			EdiOrder toEdiOrder = value.get(0);
			StringBuffer customerOrdeno = new StringBuffer();
			StringBuffer fromnoOrdeno = new StringBuffer();
			for (int i = 1; i < value.size(); i++) {
				EdiOrder eo = value.get(i);
				//合并SKU
				mergeOrderSku(eo, toEdiOrder);
				toEdiOrder.setSkulst(eo.getSkulst());
				customerOrdeno.append(":" + eo.getCustomerOrdeno());
				fromnoOrdeno.append(":" + eo.getFromno());
			}
			int skuQty = 0;
			for (EdiOrderItem ei : toEdiOrder.getSkulst()) {
				ei.setOrdeno(toEdiOrder.getOrdeno());
				skuQty += ei.getQty();
			}
			toEdiOrder.setSkuQty(skuQty);
			if (!StringUtils.isNotBlank(toEdiOrder.getFromno())) {
                toEdiOrder.setFromno(fromnoOrdeno.toString());
            } else {
                toEdiOrder.setFromno(toEdiOrder.getFromno() + fromnoOrdeno.toString());// 来源单号
            }
			toEdiOrder.setCustomerOrdeno(toEdiOrder.getCustomerOrdeno() + customerOrdeno.toString());// 商家订单号
			orders.add(toEdiOrder);
		}
		return orders;
	}

	private static final String MERGE_PARAM_SPLITER = "===KEY===";
	private static final String MERGE_PARAM_CUSTOMRE = "customerCode";
	
	/**
	 * 快递流量导入
	 * @param customerLead
	 * @param customerCode
	 * @param s
	 * @return 快递流量实体类的集合
	 */
	public static List<ExpressBillManage> getExpressBillManage(CustomerLead customerLead, String customerCode, Sheet s) {
		int rows = s.getLastRowNum();// .getRows();
		List<ExpressBillManage> expressBillManages =  new ArrayList<ExpressBillManage>();//getExpressBillManage(customerCode, rows);
		List<String> sequence = new ArrayList<String>();
		if (customerLead != null) {
			String[] keys = customerLead.getParams().split(",");
			Map<String, String> maps = new HashMap<String, String>();
			for (String key : keys) {
				String[] values = key.split(":");
				maps.put(values[0], values[1]);
			}

			// 遍历excel行
			for (int i = 0; i <= rows; i++) {
				Row xSSFRow = s.getRow(i);
				int columns = xSSFRow.getLastCellNum();
				ExpressBillManage e=new ExpressBillManage();
				// 遍历excel列
				for (int j = 0; j < columns; j++) {
					Cell cell = xSSFRow.getCell(j);
					if (cell == null) {
						continue;
					}
					String content = ExcelUtil.getCellStringValue(cell);
					if (i == 0) {
						String value = maps.get(content);
						sequence.add(value);
						continue;
					}
					String title = sequence.get(j);
					if (title == null) {
						continue;
					}
					try {
						replaceParams(title, content, e);
					} catch (Exception e2) {
						logger.error("some error.",e2);
					}

				}
				if(null!=e.getCustomerId()) expressBillManages.add(e);
			}
		}
		return expressBillManages;
	}
	
	/**
	 * 初始化空的集合
	 * @param customerCode
	 * @param rows
	 * @return
	 */
	private static List<ExpressBillManage> getExpressBillManage(String customerCode, int rows) {
		List<ExpressBillManage> expressBillManages = new ArrayList<ExpressBillManage>();
		for (int i = 0; i < rows; i++) {
			ExpressBillManage e = new ExpressBillManage();
			//e.setCustomerCode(customerCode);
			expressBillManages.add(e);
		}
		return expressBillManages;
	}
	
	/**
	 * 利用反射给实体赋值
	 * @param param
	 * @param content
	 * @param e
	 * @throws Exception
	 */
	private static void replaceParams(String param, String content, ExpressBillManage e) throws Exception {
		Field[] fields = e.getClass().getDeclaredFields();
		for (int j = 0; j < fields.length; j++) { // 遍历所有属性
			String name = fields[j].getName(); // 获取属性的名字
			if (!param.equals(name)) {
				continue;
			}
			name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
			String type = fields[j].getGenericType().toString(); // 获取属性的类型
			if (type.equals("class java.lang.String")) { // 如果type是类类型，则前面包含"class "，后面跟类名
				Method m = e.getClass().getMethod("set" + name, String.class);
				m.invoke(e, content);
			} else if (type.equals("class java.lang.Integer")) {
				int index = content.indexOf(".");
				Method m = e.getClass().getMethod("set" + name, Integer.class);
				if (index > 0) {
					m.invoke(e, Integer.parseInt(content.substring(0, index)));
				} else {
					m.invoke(e, Integer.parseInt(content));
				}

			} else if (type.equals("class java.lang.Double")) {
				Method m = e.getClass().getMethod("set" + name, Double.class);
				m.invoke(e, Double.parseDouble(content));
			}else if (type.equals("class java.util.Date")) {
				Method m = e.getClass().getMethod("set" + name, Date.class);
				m.invoke(e,DateUtils.getDate(content));
			}
			break;
		}
	}
}
